package LeetCode.leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 单词模式
 * @author: leiwenkang02@meituan.com
 * @date: 2018/8/23
 * @time: 12:45
 */
public class Test290单词规律 {
    public static void main(String[] args) {
        System.out.println(wordPattern("aba", "dog cat dog"));
    }
    public static boolean wordPattern(String pattern, String str) {
        char[] chArr = pattern.toCharArray();
        String[] strArr = str.split(" ");
        if (chArr.length != strArr.length) {
            return false;
        }
        Map<String, Character> map1 = new HashMap<>();
        Set<Character> set = new HashSet<>();
        for (int i = 0; i < strArr.length; i++) {
            if (map1.containsKey(strArr[i])) {
                if (map1.get(strArr[i]) != chArr[i]) {
                    return false;
                }
            } else {
                if (set.contains(chArr[i])) {
                    return false;
                }
                map1.put(strArr[i], chArr[i]);
            }
            set.add(chArr[i]);
        }
        return true;

    }

    public static boolean wordPattern2(String pattern, String str) {
        char[] chArr = pattern.toCharArray();
        String[] strArr = str.split(" ");
        if (chArr.length != strArr.length) {
            return false;
        }
        Map<String, Integer> map1 = new HashMap<>();
        List<Integer> list1 = new ArrayList<>();
        int j = 0;
        for (int i = 0; i < strArr.length; i++) {
            if (map1.containsKey(strArr[i])) {
                list1.add(map1.get(strArr[i]));
            } else {
                map1.put(strArr[i], j);
                list1.add(j);
                j++;
            }
        }

        Map<Character, Integer> map2 = new HashMap<>();
        List<Integer> list2 = new ArrayList<>();
        int m = 0;
        for (int n = 0; n < chArr.length; n++) {
            if (map2.containsKey(chArr[n])) {
                list2.add(map2.get(chArr[n]));
            } else {
                map2.put(chArr[n], m);
                list2.add(m);
                m++;
            }
        }
        return list1.equals(list2);


    }
}
